﻿using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace UserRepositorys
{
    public class Repository<T> : IRepository<T> where T : class, new()
    {
        private readonly ISqlSugarClient db;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="db"></param>
        public Repository(ISqlSugarClient db)
        {
            this.db = db;
        }
        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="t"></param>
        /// <returns></returns>
        public async Task<int> Addasync(T t)
        {
            return await db.Insertable<T>(t).ExecuteCommandAsync();
        }
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<int> Deleteasync(int id)
        {
            return await db.Deleteable<T>(id).In(id).ExecuteCommandAsync();
        }
        /// <summary>
        /// 查询全部
        /// </summary>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public Task<List<T>> GetAllasync()
        {
            return db.Queryable<T>().ToListAsync();
        }

        /// <summary>
        /// 条件查询
        /// </summary>
        /// <param name="expression"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<List<T>> GetAllAsync(Expression<Func<T, bool>> expression)
        {
            return await db.Queryable<T>().Where(expression).ToListAsync();
        }
        /// <summary>
        ///主键查询
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<T> GetModelasync(int id)
        {
            return await db.Queryable<T>().InSingleAsync(id);
        }
        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="t"></param>
        /// <returns></returns>
        public async Task<int> Updateasync(T t)
        {
            return await db.Updateable<T>(t).ExecuteCommandAsync();
        }
    }
}
